<?php

namespace app\admin\controller\knowbase;

use app\common\controller\Backend;
use think\Db;
use think\exception\DbException;
use think\response\Json;

/**
 * 操作日志
 *
 * @icon fa fa-circle-o
 */
class Progress extends Backend
{

    /**
     * Progress模型对象
     * @var \app\common\model\knowbase\Progress
     */
    protected $model = null;
    protected $relationSearch = true;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\common\model\knowbase\Progress;
        $this->view->assign("typeList", $this->model->getTypeList());
    }

    /**
     * 删除指定天数的历史版本记录
     */
    public function remove() {
        $day = $this->request->post('day',0,'intval');
        if ($day<0) {
            $this->error(__('error_not_day'));
        }

        if ($day>0) {
            $this->model->whereRaw('createtime<unix_timestamp()-'.$day*86400);
        }

        try {
            if ($day==0) {
                Db::query("TRUNCATE TABLE  ".$this->model->getTable());
            } else {
                $this->model->delete();
            }
            \app\common\model\knowbase\Progress::addLog('progress_history_delete',0,$day==0?'删除全部':'删除'.$day.'天前');
        } catch (\Exception $e){
            $this->error($e->getMessage());
        }
        $this->success(__('success_handle'));
    }

    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */

    /**
     * 查看
     *
     * @return string|Json
     * @throws \think\Exception
     * @throws DbException
     */
    public function index()
    {
       
        $this->request->filter(['strip_tags', 'trim']);
        if (false === $this->request->isAjax()) {
            return $this->view->fetch();
        }
       
        if ($this->request->request('keyField')) {
            return $this->selectpage();
        }
        [$where, $sort, $order, $offset, $limit] = $this->buildparams();
        $list = $this->model
            ->with(['admin'=>function($q){
                return $q->withField('id,username');
            }])
            ->where($where)
            ->order($sort, $order)
            ->paginate($limit);
        $result = ['total' => $list->total(), 'rows' => $list->items()];
        return json($result);
    }
}
